<?php
    require_once("../classes/Database.php");
	require_once("../classes/User.php");
	
	$db = new Database("localhost", "root", "");
	$user = new User();
	
	if(!empty($_POST["name"]) && !empty($_POST["user"]) && !empty($_POST["pass"]) && !empty($_POST["mail"]) && !empty($_POST["role"])){
		$username = $_POST["user"];
		$db->connect("emprego");
		$db->executeQuery("SELECT username FROM users WHERE username='$username'");
	
		session_start();
				
		if(!($db->getResultLine(MYSQL_ASSOC))){
			$name = $_POST["name"];
			$username = $_POST["user"];
			$pass = $_POST["pass"];
			$encryptPass = md5($pass);
			$mail = $_POST["mail"];
			$role = $_POST["role"];
			
			$user->setName($name);
			$user->setUsername($username);
			$user->setPassword($encryptPass);
			$dateArray = getdate();
			$date = $dateArray["year"] . "-" . $dateArray["month"] . "-" . $dateArray["mday"] . " "
					. $dateArray["hours"] . ":" . $dateArray["minutes"] . ":" . $dateArray["seconds"];
			$user->setUpdateDate($date);
			$user->setSaveDate($date);
			$user->setEmail($mail);
			$user->setRole($role);
			$user->setSuper(FALSE);
			
			$db->executeQuery("INSERT INTO users(nome, username, password, update_date, save_date, email, roles, is_super) VALUES('$name', '$username', '$encryptPass', now(), now(), '$mail', '$role', 0)");
			$db->disconnect();
			
			$_SESSION["user"] = $user;
			$_SESSION["login"] = TRUE;
			header("Location: ../home.php");
		}else{
			$db->disconnect();
			$_SESSION["user"] = "";
			$_SESSION["login"] = FALSE;
			$_SESSION["msg"] = "ERRO: Username j&aacute existe";
			header("Location: ../signup.php");
		}
	}else{
		$_SESSION["user"] = "";
		$_SESSION["login"] = FALSE;
		$_SESSION["msg"] = "ERRO: Introduza todos os dados";
		header("Location: ../signup.php");
	}
?>